<template>
  <div class="bind-form-container p-4">
    <!-- <div class="mb-4">
      <p><span class="font-medium">用户ID:</span> {{ row.Id }}</p>
      <p><span class="font-medium">用户名:</span> {{ row.Name }}</p>
    </div> -->

    <PureTableBar title="" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button
          type="primary"
          style="width: 80px"
          :icon="useRenderIcon('ri/add-line')"
          @click="handleAdd"
        >
          新增绑定
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="Id"
          style="height: 350px"
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          align-whole="center"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon('ri/edit-line')"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`是否确认删除ID为${row.Id}的登录绑定`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon('ri/delete-bin-line')"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
          <template #status="{ row }">
            <el-switch
              v-model="row.Disabled"
              :loading="toggleLoading[row.Id]"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="0"
              :inactive-value="1"
              active-text="启用"
              inactive-text="停用"
              inline-prompt
              class="ml-2"
              style="
                --el-switch-on-color: #13ce66;
                --el-switch-off-color: #ff4949;
              "
              @change="() => toggleStatus(row)"
            />
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <el-dialog
      v-model="dialogVisible"
      title="新增登录绑定"
      width="500px"
      :before-close="handleClose"
      draggable
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="登录类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择登录类型">
            <el-option
              v-for="option in loginTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否禁用" prop="disabled">
          <el-radio-group v-model="formData.disabled">
            <el-radio :value="0">不禁用</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="code1Label" prop="code1">
          <el-input
            v-model="formData.code1"
            :placeholder="`请输入${code1Label}`"
          />
        </el-form-item>
        <el-form-item v-if="showCode2" :label="code2Label" prop="code2">
          <el-input
            v-model="formData.code2"
            :placeholder="`请输入${code2Label}`"
          />
        </el-form-item>
        <el-form-item v-if="showCode3" :label="code3Label" prop="code3">
          <el-input
            v-model="formData.code3"
            :placeholder="`请输入${code3Label}`"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, reactive, onMounted, computed } from "vue";
import {
  ElMessage,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadio,
  ElRadioGroup,
  ElMessageBox,
  ElSelect,
  ElOption
} from "element-plus";
import { PureTable } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { PaginationProps } from "@pureadmin/table";
import type { UserItem } from "../componentsUtils/type/userTypes";
import type { FormInstance } from "element-plus";
const loginTypeOptions = [
  { label: "账号", value: 0 },
  { label: "IMEI", value: 1 },
  { label: "SN", value: 2 },
  { label: "QRCode", value: 3 },
  { label: "机器码", value: 4 },
  { label: "手机号", value: 5 },
  { label: "邮箱号", value: 6 }
];
// 计算主关联码标签文本
const code1Label = computed(() => {
  const labelMap: Record<number, string> = {
    0: "登录账号",
    1: "IMEI",
    2: "SN",
    3: "二维码地址",
    4: "机器码",
    5: "手机号",
    6: "邮箱"
  };
  return labelMap[formData.type] || "主关联码";
});

// 计算从关联码标签文本
const code2Label = computed(() => {
  const labelMap: Record<number, string> = {
    0: "登录密码",
    1: "ICCID"
  };
  return labelMap[formData.type] || "从关联码";
});

// 计算三关联码标签文本
const code3Label = computed(() => {
  return formData.type === 0 ? "加密盐" : "三关联码";
});

// 计算是否显示从关联码
const showCode2 = computed(() => {
  return formData.type === 0 || formData.type === 1;
});

// 计算是否显示三关联码
const showCode3 = computed(() => {
  return formData.type === 0;
});
// 定义登录绑定数据类型
interface LoginBindItem {
  Id: number;
  CreateTime: string;
  UserId: number;
  DealerId: number;
  TenantId: number;
  Type: number;
  Code1: string;
  Code2: string;
  Code3: string;
  Disabled: number;
}
// 定义表单数据类型
interface FormDataType {
  type: number;
  disabled: number;
  code1: string;
  code2: string;
  code3: string;
}
// 新增表单相关
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive<FormDataType>({
  type: 1, // 默认账号登录
  disabled: 0, // 默认不禁用
  code1: "",
  code2: "",
  code3: ""
});
// 添加一个变量来标识当前是新增还是编辑模式，以及存储当前编辑的ID
const editMode = ref(false);
const currentId = ref(0);
// 表单验证规则
const rules = {
  type: [
    {
      required: true,
      message: "请选择登录类型",
      trigger: "change"
    }
  ],
  code1: [
    {
      required: true,
      message: "请输入主关联码",
      trigger: "blur"
    }
  ]
};
// 定义props
const props = defineProps<{
  row: UserItem;
}>();

const tableRef = ref();
const loading = ref(false);
const dataList = ref<LoginBindItem[]>([]);
// 添加toggleLoading对象用于管理每行的加载状态
const toggleLoading = ref<Record<number, boolean>>({});
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});

// 列表列定义
const columns = [
  {
    label: "类型",
    prop: "Type",
    width: 100,
    formatter: (row: LoginBindItem) => {
      const typeMap = {
        0: "账号",
        1: "IMEI",
        2: "SN",
        3: "QRCode",
        4: "机器码",
        5: "手机号",
        6: "邮箱号"
      };
      return typeMap[row.Type as keyof typeof typeMap] || "未知类型";
    }
  },
  {
    label: "Code1",
    prop: "Code1",
    minWidth: 120
  },
  {
    label: "Code2",
    prop: "Code2",
    minWidth: 120
  },
  {
    label: "Code3",
    prop: "Code3",
    minWidth: 120
  },
  {
    label: "状态",
    prop: "Disabled",
    width: 100,
    slot: "status"
  },
  {
    label: "创建时间",
    prop: "CreateTime",
    width: 180
  },
  {
    label: "操作",
    fixed: "right" as const,
    width: 120,
    slot: "operation"
  }
];

// 获取登录绑定列表
function onSearch() {
  loading.value = true;
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    userId: props.row.Id
  };

  http
    .get(changeHttpLink("/api/UserLoginBind"), {
      params
    })
    .then((res: any) => {
      loading.value = false;
      console.log("登录绑定列表:", res.Data.Items);
      if (res.Success) {
        // 确保Disabled字段为数字类型，以兼容el-switch组件
        const items = (res.Data.Items || []).map((item: any) => ({
          ...item,
          Disabled: Number(item.Disabled) // 确保为数字类型
        }));
        dataList.value = items;
        pagination.total = res.Data.TotalCount || 0;
      } else {
        ElMessage.error(res.Message || "获取登录绑定列表失败");
      }
    })
    .catch(err => {
      loading.value = false;
      ElMessage.error("获取登录绑定列表失败");
      console.error("获取登录绑定列表失败:", err);
    });
}

// 分页大小变化
function handleSizeChange(val: number) {
  pagination.currentPage = 1;
  pagination.pageSize = val;
  onSearch();
}

// 处理当前页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val;
  onSearch();
}
// 状态切换方法
defineExpose({ toggleStatus });
function toggleStatus(row: LoginBindItem) {
  // 计算当前状态和要切换到的状态
  // Disabled: 0=启用, 1=禁用
  const isCurrentlyDisabled = row.Disabled === 1;
  const newStatusText = isCurrentlyDisabled ? "启用" : "停用";

  // 显示确认对话框
  ElMessageBox.confirm(
    `确认要<strong>${newStatusText}</strong><strong style='color:var(--el-color-primary)'>用户Id为${row.UserId}的登录绑定吗?</strong>`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  )
    .then(() => {
      // 设置加载状态
      toggleLoading.value[row.Id] = true;

      // 计算要发送给接口的enabled值（布尔类型）
      // 如果当前是正常状态(Disabled=0)，则要启用(enabled=true)
      // 如果当前是禁用状态(Disabled=1)，则要禁用(enabled=false)
      const enabledValue = row.Disabled === 0 ? 0 : 1;
      const params = {
        id: row.Id,
        enabled: enabledValue // 发送布尔值给接口
      };
      http
        .request(
          "patch",
          changeHttpLink(`/api/UserLoginBind/${row.Id}/toggle`),
          {
            data: {
              params
            }
          }
        )
        .then((response: any) => {
          toggleLoading.value[row.Id] = false;
          if (response.Success) {
            ElMessage.success("状态切换成功");
            onSearch(); // 重新获取数据以确保状态同步
          } else {
            // 失败时恢复原状态
            console.log("接口返回失败，恢复原状态");
            row.Disabled = row.Disabled === 0 ? 1 : 0; // 恢复为切换前的状态
            ElMessage.error(response.Message || "状态切换失败");
          }
        })
        .catch(error => {
          // 异常时恢复原状态
          console.log("请求异常，恢复原状态:", error);
          row.Disabled = row.Disabled === 0 ? 1 : 0; // 恢复为切换前的状态
          toggleLoading.value[row.Id] = false;
          ElMessage.error("网络异常，状态切换失败");
          console.error("状态切换失败:", error);
        });
    })
    .catch(() => {
      // 取消操作时恢复原状态
      console.log("用户取消操作，恢复原状态");
      row.Disabled = row.Disabled === 0 ? 1 : 0; // 恢复为切换前的状态
    });
}
// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  formData.type = 1;
  formData.disabled = 0;
  formData.code1 = "";
  formData.code2 = "";
  formData.code3 = "";
}
// 新增登录绑定
function handleAdd() {
  resetForm();
  editMode.value = false;
  currentId.value = 0;
  dialogVisible.value = true;
}
// 关闭对话框
function handleClose() {
  dialogVisible.value = false;
  resetForm();
  editMode.value = false;
  currentId.value = 0;
}
function handleSubmit() {
  if (!formRef.value) return;

  formRef.value.validate(valid => {
    if (valid) {
      // 准备提交数据
      const Data = {
        ...formData,
        userId: props.row.Id,
        tenantId: props.row.TenantId,
        dealerId: props.row.DealerId
        // 这里可以根据需要添加其他必要的字段
      };

      loading.value = true;
      // 根据是否是编辑模式调用不同的API
      if (editMode.value) {
        // 编辑模式：使用put请求
        http
          .request(
            "put",
            changeHttpLink(`/api/UserLoginBind/${currentId.value}`),
            {
              data: Data
            }
          )
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              ElMessage.success("编辑登录绑定成功");
              dialogVisible.value = false;
              onSearch(); // 重新加载列表
            } else {
              ElMessage.error(res.Message || "编辑登录绑定失败");
            }
          })
          .catch(err => {
            loading.value = false;
            ElMessage.error("编辑登录绑定失败");
            console.error("编辑登录绑定失败:", err);
          });
      } else {
        // 新增模式：使用post请求
        http
          .post(changeHttpLink("/api/UserLoginBind"), {
            data: Data
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              ElMessage.success("新增登录绑定成功");
              dialogVisible.value = false;
              onSearch(); // 重新加载列表
            } else {
              ElMessage.error(res.Message || "新增登录绑定失败");
            }
          })
          .catch(err => {
            loading.value = false;
            ElMessage.error("新增登录绑定失败");
            console.error("新增登录绑定失败:", err);
          });
      }
    }
  });
}
function handleEdit(row: LoginBindItem) {
  resetForm();
  // 填充表单数据
  formData.type = row.Type;
  formData.disabled = row.Disabled;
  formData.code1 = row.Code1;
  formData.code2 = row.Code2;
  formData.code3 = row.Code3;
  // 设置为编辑模式并存储当前ID
  editMode.value = true;
  currentId.value = row.Id;
  // 打开对话框
  dialogVisible.value = true;
}

// 删除登录绑定
function handleDelete(row: LoginBindItem) {
  ElMessageBox.confirm(`是否确认删除ID为${row.Id}的登录绑定数据`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      loading.value = true;
      http
        .request("delete", changeHttpLink(`/api/UserLoginBind/${row.Id}`), {
          data: row.Id
        })
        .then((res: any) => {
          loading.value = false;
          if (res.Success) {
            ElMessage.success(`删除登录绑定成功`);
            onSearch(); // 重新加载列表
          } else {
            ElMessage.error(res.Message || "删除登录绑定失败");
          }
        })
        .catch(err => {
          loading.value = false;
          ElMessage.error("删除登录绑定失败");
          console.error("删除登录绑定失败:", err);
        });
    })
    .catch(() => {
      // 取消操作，不做任何处理
    });
}

// 组件挂载时加载数据
onMounted(() => {
  onSearch();
  console.log("用户数据:", props.row);
});
</script>

<style scoped>
.login-bind-container {
  width: 100%;
  height: 100%;
}
.bind-form-container {
  width: 100%;
}
</style>
